<template>
  <j-modal
    width="80%"
    title="社保方案"
    :maskClosable="false"
    switchFullscreen
    :visible.sync="editModalVisible"
    @cancel="handleCancleDbSync"
    >
    <template slot="footer">
      <a-button @click="handleCancleDbSync">关闭</a-button>
      <a-button type="primary" :loading="syncLoading" @click="handleDbSync">确认</a-button>
    </template>
    <div class="table-page-search-wrapper warp">
    <a-form-model
      layout="inline"
      labelAlign="right"
      ref="ruleForm"
      :model="formData"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-row :gutter="24">
        <a-col :xl="8" :lg="8" :md="8" :sm="24" >
          <a-form-model-item label="方案编码" prop="templateCode">
            <a-input :disabled="disableSubmit" v-model="formData.templateCode" placeholder="请输入方案编码"/>
          </a-form-model-item>
        </a-col>
        <a-col :xl="8" :lg="8" :md="8" :sm="24" >
          <a-form-model-item label="方案名称" prop="templateName">
            <a-input :disabled="disableSubmit" v-model="formData.templateName" placeholder="请输入方案名称"/>
          </a-form-model-item>
        </a-col>
        <a-col :xl="8" :lg="8" :md="8" :sm="24">
          <a-form-model-item label="缴纳城市">
            <j-dict-select-tag
              :disabled="disableSubmit"
              v-model="formData.baseCity"
              placeholder="请选择缴纳城市"
              dict-code="hr_base_city"
            >
            </j-dict-select-tag>
          </a-form-model-item>
        </a-col>
        <a-col :xl="16" :lg="16" :md="16" :sm="24">
          <a-form-model-item label="社保公积金项目">
            <a-checkbox-group v-model="formData.item">
              <template v-for="(item,i) in plainOptions">
                <a-checkbox :key="i" :value="item.value">{{item.text}}</a-checkbox>
              </template>
            </a-checkbox-group>
          </a-form-model-item>
        </a-col>
        <a-col :xl="8" :lg="8" :md="8" :sm="24">
          <a-form-model-item label="状态">
            <a-switch v-model="formData.templateStatus" />
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    </div>
    <vxe-grid
      ref="xTable"
      border
      resizable
      keep-source
      :columns="tableColumn"
      :data="tableData"
      :edit-rules="validRules"
      :min-height="200"
      :edit-config="{trigger: 'click', mode: 'row',showStatus: true}"
    >
    </vxe-grid>
  </j-modal>
</template>
<script>
import { postAction, putAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import { initDictOptions, filterDictTextByCache } from '@/components/dict/JDictSelectUtil'
export default {
  data() {
    return {
      editModalVisible: false,
      disableSubmit: false,
      loading: false,
      syncLoading: false,
      url: {
        add: '/hr/insurance/template/addWithChildren',
        edit: '/hr/insurance/template/editWithChildren',
        insuranceTemplateDetail: '/hr/insurance/template/listInsuranceTemplateDetailByTemplateCode'
      },
      tableColumn: [
        { type: 'seq', width: 60 },
        { field: 'insuranceType', title: '类型', slots: { default: ({ row }) => {
          return filterDictTextByCache('hr_insurance_type', row.insuranceType)
        } }},
        {
          title: '缴纳基数',
          align: 'center',
          children: [
            { title: '基数下限', field: 'baseUpper', editRender: { name: '$input', props: { type: 'number' }}},
            { title: '基数上限', field: 'baseLower', editRender: { name: '$input', props: { type: 'number' }}}
          ]
        },
        {
          title: '缴纳比例',
          align: 'center',
          children: [
            { title: '个人比例', field: 'personalScale', editRender: { name: '$input', props: { type: 'number' }}},
            { title: '公司比例', field: 'companyScale', editRender: { name: '$input', props: { type: 'number' }}}
          ]
        },
        {
          title: '缴费常量',
          align: 'center',
          children: [
            { title: '个人常量', field: 'personalConstant', editRender: { name: '$input', props: { type: 'number' }}},
            { title: '公司常量', field: 'companyConstant', editRender: { name: '$input', props: { type: 'number' }}}
          ]
        }
      ],
      rules: {
        templateName: [
          { required: true, message: '请输入方案编码', trigger: 'blur' }
        ],
        templateCode: [
          { required: true, message: '请输入方案名称', trigger: 'blur' },
          { validator: (rule, value, callback) => validateDuplicateValue('hr_insurance_template', 'template_code', value, this.formData.id, callback) }
        ]
      },
      formData: {},
      plainOptions: [],
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      tableData: [],
      validRules: {
        baseUpper: [
          { required: true, message: '请填写基数下限' },
          { validator: this.baseUpper },
          { min: 0, type: 'number', message: '请填写大于0的数字' }
        ],
        baseLower: [
          { required: true, message: '请填写基数上限' },
          { min: 0, type: 'number', message: '请填写大于0的数字' }
        ],
        personalScale: [
          { required: true, message: '请填写个人比例' },
          { pattern: /^100$|^(\d|[1-9]\d)(\.\d+)*$/, message: '请输入0-100的数字' }
          // { max: 100, type: 'number', message: '请填写小于等于0的数字' }
        ],
        companyScale: [
          { required: true, message: '请填写公司比例' },
          { pattern: /^100$|^(\d|[1-9]\d)(\.\d+)*$/, message: '请输入0-100的数字' }
        ],
        personalConstant: [
          { min: 0, type: 'number', message: '请填写大于0的数字' }
        ],
        companyConstant: [
          { min: 0, type: 'number', message: '请填写大于0的数字' }
        ]
      },
      dictOptions: [],
      dictCode: 'hr_insurance_type',
      flag: true// 判断社保项目变化时 是否改变社保明细
    }
  },
  watch: {
    'formData.item'(val, oldVal) {
      if (!this.flag) {
        this.flag = true
        return false
      }
      oldVal = oldVal || []
      val = val || []
      if (val.length > oldVal.length) {
        val.forEach(item => {
          if (oldVal.indexOf(item) < 0) {
            const obj = {
              insuranceType: this.plainOptions[item].value
            }
            this.$refs.xTable.insertAt(obj, -1)
          }
        })
      } else {
        oldVal.forEach(item => {
          if (val.indexOf(item) < 0) {
            const { fullData } = this.$refs.xTable.getTableData()
            fullData.forEach(row => {
              if (row.insuranceType === item) {
                this.$refs.xTable.remove(row)
              }
            })
          }
        })
      }
    }
  },
  methods: {
    baseUpper({ cellValue, row }) {
      if (cellValue && row.baseLower && Number(cellValue) >= Number(row.baseLower)) {
        return new Error('基数下限必须小于基数上限')
      }
    },
    handleCancleDbSync() {
      this.disableSubmit = false
      this.editModalVisible = false
    },
    edit(data) {
      this.formData = JSON.parse(JSON.stringify(data))
      this.getInsuranceTemplateDetail(this.formData.templateCode)
      this.editModalVisible = true
    },
    add() {
      this.formData = {}
      this.tableData = []
      this.editModalVisible = true
    },
    getInsuranceTemplateDetail(templateCode) { // 获取社保明细表数据
      getAction(this.url.insuranceTemplateDetail, { templateCode: templateCode }).then(res => {
        if (res.success) {
          this.tableData = res.result.records
          const items = []
          this.tableData.forEach(item => {
            items.push(item.insuranceType)
          })
          this.flag = false
          this.$set(this.formData, 'item', items)
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    handleDbSync() { // 弹窗点击确定
      Promise.all([
        this.$refs.xTable.fullValidate(),
        this.$refs['ruleForm'].validate()
      ]).then((res) => {
        this.updateData()
      }).catch(function(reason) {
        console.log(reason)
      })
    },
    updateData() { // 保存提交数据
      const { fullData } = this.$refs.xTable.getTableData()
      this.formData.insuranceTemplateDetails = fullData
      this.syncLoading = true
      if (this.formData.id) {
        putAction(this.url.edit, this.formData).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.editModalVisible = false
            this.$emit('ok')
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.syncLoading = false
        })
      } else {
        postAction(this.url.add, this.formData).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.editModalVisible = false
            this.$emit('ok')
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.syncLoading = false
        })
      }
    },
    initDictData() {
      // 根据字典Code, 初始化字典数组
      initDictOptions(this.dictCode).then((res) => {
        if (res.success) {
          this.plainOptions = res.result
        }
      })
    }
  },
  mounted() {
    this.initDictData()
  }
}
</script>
